﻿using Autofac;
using System.ComponentModel;
using System.Windows;

namespace Super.Hmi.Utils
{
    /// <summary>
    /// ViewModelLocator 是一个附加属性类，用于自动将视图与其对应的视图模型绑定。
    /// </summary>
    public static class ViewModelLocator
    {
        public static bool GetAutoWireViewModel(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoWireViewModelProperty);
        }
        public static void SetAutoWireViewModel(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoWireViewModelProperty, value);
        }
        /// <summary>
        /// 是否 View 和 ViewModel 自动绑定
        /// </summary>
        public static readonly DependencyProperty AutoWireViewModelProperty = DependencyProperty.RegisterAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), new PropertyMetadata(false, AutoWireViewModelChanged));
        /// <summary>
        /// 自动绑定 ViewModel 到 View 的 DataContext。
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void AutoWireViewModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(d)) return;

            var viewType = d.GetType();
            var viewName = viewType.FullName;
            var viewAssemblyName = viewType.Assembly.FullName;
            var viewModelName = $"{viewName}Model, {viewAssemblyName}";
            var viewModelType = Type.GetType(viewModelName);

            if (viewModelType == null)
            {
                // 尝试第二种命名约定：View替换为ViewModel
                viewModelName = viewName.Replace("View", "ViewModel");
                viewModelType = Type.GetType(viewModelName);
            }

            if (viewModelType == null) return;

            try
            {
                var container = ((App)Application.Current).Container;
                var viewModel = container.Resolve(viewModelType);
                ((FrameworkElement)d).DataContext = viewModel;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"View -- ViewModel 绑定错误: {ex.Message}");
            }
        }
    }
}
